import java.io.DataInputStream
import java.io.InputStream
import java.util.concurrent.CountDownLatch

class Receiver(private val inputStream: InputStream, private val sb: StringBuilder, private val countDownLatch: CountDownLatch) : Runnable {

    override fun run() {
        try {
            receive()
        } catch (e: Exception) {
            printMessage(sb, "接收者（上传）出现异常, ${e.javaClass.simpleName}: ${e.message}")
            e.printStackTrace()
        } finally {
            countDownLatch.countDown()
        }
    }

    private fun receive() {
        val fileSize = DataInputStream(inputStream).readLong()
        printMessage(sb, "服务器准备接收客户端视频文件(${formatFileSize(fileSize)})")
        var receivePerSecond = 0L // 每秒接收数据大小
        var totalReceive = 0L     // 累计接收数据大小
        val buf = ByteArray(1024 * 8)
        var length: Int
        var start = System.currentTimeMillis()
        val startTime = start
        while (inputStream.read(buf).also { length = it } != -1) {
            receivePerSecond += length
            totalReceive += length

            if (System.currentTimeMillis() - start >= 1000L) {
                printReceiveSpeed(receivePerSecond, totalReceive, fileSize)
                start = System.currentTimeMillis()
                receivePerSecond = 0
            } else if (totalReceive == fileSize) {
                val second = (System.currentTimeMillis() - start) / 1000f // 把毫秒换成秒
                receivePerSecond = (receivePerSecond / second).toLong()   // 因为这次的接收的数据还没用到1秒的时间，所以要换算一下
                printReceiveSpeed(receivePerSecond, totalReceive, fileSize)
                val totalUseTime = (System.currentTimeMillis() - startTime) / 1000f
                printMessage(sb, "服务器接收视频文件${formatFileSize(fileSize)}完成，总计用时：${totalUseTime}秒，平均${formatFileSize((fileSize / totalUseTime).toLong())}/s")
                break
            }
        }
    }

    private fun printReceiveSpeed(receive: Long, total: Long, fileSize: Long) {
        val receivePerSecond = formatFileSize(receive)
        val totalReceive = formatFileSize(total)
        val fileLength = formatFileSize(fileSize)
        val percent = total * 100 / fileSize
        printMessage(sb, "↑ $receivePerSecond/s，$totalReceive/$fileLength($percent%)")
    }

}